<template>
  <div class="system-user-dialog-container">
    <el-dialog v-model="state.dialog.isShowDialog" :title="state.dialog.title" width="1200px">
      <el-form ref="userDialogFormRef" :model="state.ruleForm" :rules="rules" label-width="100px" size="default">
        <el-row :gutter="35">
          <el-col :span="8" class="mb20">
            <el-form-item label="券名称" prop="couponName">
              <el-input v-model="state.ruleForm.couponName"
                        :disabled="formReadonly" clearable
                        placeholder="请输入券名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="mb20">
            <el-form-item label="券类型" prop="couponType">
              <el-select v-model="state.ruleForm.couponType" clearable placeholder="请选择券类型"
                         size="default">
                <el-option
                    v-for="item in state.typeList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="mb20">
            <el-form-item label="排序" prop="orderNumber">
              <el-input v-model="state.ruleForm.orderNumber"
                        :disabled="formReadonly" clearable
                        placeholder="请输入排序"
                        type="number"/>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="mb20">
            <el-form-item label="消费金额" prop="consumptionAmount">
              <el-input v-model="state.ruleForm.consumptionAmount"
                        :disabled="formReadonly"
                        clearable placeholder="请输入消费金额"
                        type="number"/>
            </el-form-item>
          </el-col>
          <el-col v-show="state.ruleForm.couponType !== '4'" :span="8" class="mb20">
            <el-form-item label="优惠金额" prop="discountAmount">
              <el-input v-model="state.ruleForm.discountAmount"
                        :disabled="formReadonly"
                        clearable placeholder="请输入优惠金额"
                        type="number"/>
            </el-form-item>
          </el-col>
          <el-col v-show="state.ruleForm.couponType === '4'" :span="8" class="mb20">
            <el-form-item label="折扣比例" prop="discountRatio">
              <el-input v-model="state.ruleForm.discountRatio"
                        :disabled="formReadonly"
                        clearable placeholder="请输入折扣比例"
                        type="number"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="mb20">
            <el-form-item label="周几限制：" prop="daysLimit">
              <el-checkbox-group v-model="state.ruleForm.checkedDayIds">
                <el-checkbox v-for="item in state.daysList" :key="item.dictValue" :disabled="formReadonly"
                             :label="item.dictValue + ''">{{
                    item.dictLabel
                  }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col v-show="state.ruleForm.couponType === '2'" :span="8" class="mb20">
            <el-form-item label="可用商品" prop="availableStore">
              <el-select v-model="state.ruleForm.ableStoreList" clearable
                         multiple
                         placeholder="请选择可用商品"
                         size="default">
                <el-option
                    v-for="item in state.storeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id+''"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-show="state.ruleForm.couponType === '3'" :span="8" class="mb20">
            <el-form-item label="可用服务" prop="availableServer">
              <el-select v-model="state.ruleForm.ableServerList" clearable
                         multiple
                         placeholder="请选择可用服务"
                         size="default">
                <el-option
                    v-for="item in state.serverList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id+''"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="mb20">
            <el-form-item label="能否转赠" prop="transferable">
              <el-select v-model="state.ruleForm.transferable" clearable
                         placeholder="能否转赠"
                         size="default">
                <el-option
                    v-for="item in state.yesOrNo"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="mb20">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                  v-model="state.ruleForm.startTime"
                  placeholder="开始时间"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" class="mb20">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                  v-model="state.ruleForm.endTime"
                  placeholder="结束时间"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" class="mb20">
            <el-form-item label="使用目的" prop="purpose">
              <el-input v-model="state.ruleForm.purpose"
                        :disabled="formReadonly" clearable
                        placeholder="请输入使用目的"/>
            </el-form-item>
          </el-col>
          <el-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24" class="mb20">
            <el-form-item label="使用说明" prop="instructions">
              <el-input v-model="state.ruleForm.instructions" :disabled="formReadonly" maxlength="150"
                        placeholder="请输入使用说明"
                        type="textarea"/>
            </el-form-item>
          </el-col>
          <el-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24" class="mb20">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="state.ruleForm.remark" :disabled="formReadonly" maxlength="150"
                        placeholder="请输入备注"
                        type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button size="default" @click="onCancel">取 消</el-button>
					<el-button size="default" type="primary" @click="onSubmit(userDialogFormRef)">
						{{ state.dialog.submitTxt }}
					</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" name="systemUserDialog" setup>
import {computed, nextTick, onMounted, reactive, ref} from 'vue';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage} from 'element-plus';
import {dictDataApi} from "/@/api/sys/dictData";
import {commodityApi} from "/@/api/store/commodity";
import {serverApi} from "/@/api/store/server";
import {couponTemplateApi} from "/src/api/market/coupon/template";
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const userDialogFormRef = ref();
const state = reactive({
  ruleForm: {
    couponName: '', // 券名称
    couponType: '', // 券类型
    consumptionAmount: '',
    discountAmount: '',
    discountRatio: '',
    startTime: '',
    endTime: '', //结束时间
    daysLimit: '',
    availableStore: '',
    availableServer: '',
    transferable: '',
    purpose: '',
    instructions: '',
    background: '',
    orderNumber: '',
    remark: '', // 备注
    ableStoreList: [],
    ableServerList: [],
    checkedDayIds: [], // 已选星期几
  },
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
  typeList: [],
  daysList: [], // 星期列表
  storeList: [], //商品列表
  serverList: [], //服务列表
  yesOrNo: [],
});
const rules = reactive<FormRules>({
  couponName: [{required: true, message: '不能为空', trigger: 'blur'}],
  couponType: [{required: true, message: '不能为空', trigger: 'blur'}],
  consumptionAmount: [{required: true, message: '不能为空', trigger: 'blur'}],
  startTime: [{required: true, message: '不能为空', trigger: 'blur'}],
  endTime: [{required: true, message: '不能为空', trigger: 'blur'}],
  transferable: [{required: true, message: '不能为空', trigger: 'blur'}],
});
// 打开弹窗
const openDialog = (type: string, row: RowUserType) => {
  state.dialog.type = type;
  state.dialog.isShowDialog = true;
  state.ruleForm.ableStoreList = [];
  state.ruleForm.ableServerList = [];
  state.ruleForm.checkedDayIds = [];
  if (type === 'edit') {
    state.dialog.title = '修改券模版';
    state.dialog.submitTxt = '修 改';
    couponTemplateApi()
        .getInfo(row.id)
        .then(res => {
          state.ruleForm.ableStoreList = res.data.availableStore.split(',');
          state.ruleForm.ableServerList = res.data.availableServer.split(',');
          state.ruleForm.checkedDayIds = res.data.daysLimit.split(',');
        })
  } else if (type === 'add') {
    state.dialog.title = '新增券模版';
    state.dialog.submitTxt = '新 增';
  }
  nextTick(() => {
    if (type === 'add') {
      // 清空表单，此项需加表单验证才能使用
      userDialogFormRef.value.resetFields();
    } else {
      state.ruleForm = Object.assign(state.ruleForm, row);
    }
  });
};
// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
  closeDialog();
};
// 提交
const onSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (state.dialog.type === 'add') {
        couponTemplateApi()
            .addRecord(state.ruleForm)
            .then((res) => {
              if (res && res.code === 200) {
                ElMessage.success(res.msg || '新增成功');
                closeDialog();
                emit('refresh');
              }
            });
      } else if (state.dialog.type === 'edit') {
        couponTemplateApi()
            .updateRecord(state.ruleForm)
            .then((res) => {
              if (res && res.code === 200) {
                ElMessage.success(res.msg || '修改成功');
                closeDialog();
                emit('refresh');
              }
            });
      }
    }
  });
};

// 页面加载时
onMounted(() => {

  // 券分类
  dictDataApi()
      .getDictByType("coupon_type")
      .then(res => {
        state.typeList = res.data;
      })

  // 券分类
  dictDataApi()
      .getDictByType("week")
      .then(res => {
        state.daysList = res.data;
      })

  // 系统是否
  dictDataApi()
      .getDictByType("sys_yes_no")
      .then(res => {
        state.yesOrNo = res.data;
      })

  // 商品列表
  commodityApi()
      .findAll()
      .then(res => {
        state.storeList = res.data;
      })

  // 服务列表
  serverApi()
      .findAll()
      .then(res => {
        state.serverList = res.data;
      })
});

const formReadonly = computed(() => {
  return state.dialog.type !== 'add' && state.dialog.type !== 'edit'
})
// 暴露变量
defineExpose({
  openDialog,
});
</script>
